package com.zwb.boot.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zwb.boot.common.R;
import com.zwb.boot.dto.SetmealDto;
import com.zwb.boot.entity.Setmeal;
import com.zwb.boot.entity.SetmealDish;
import com.zwb.boot.service.CategoryService;
import com.zwb.boot.service.SetmealDishService;
import com.zwb.boot.service.SetmealService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 头发又黑又长
 * @Date 2022/7/23 20:38
 * @email zwb15083976291@163.com
 */
@CacheConfig(cacheNames = {"setmealCache"})
@Api("套餐管理")
@RestController
@RequestMapping("/setmeal")
public class SetmealController {

    @Autowired
    private SetmealService setmealService;

    @Autowired
    private SetmealDishService setmealDishService;

    @Autowired
    private CategoryService categoryService;

    /**
     * 添加套餐
     *
     * @return
     */
    /* 删除所有的缓存数据 */
    @CacheEvict(allEntries = true)
    @ApiOperation(value = "添加套餐接口")
    @PostMapping
    public R<String> save(@RequestBody SetmealDto setmealDto) {
        setmealService.saveWithSetmealDish(setmealDto);
        return R.success("添加套餐成功");

    }

    @ApiOperation("套餐分页数据接口")
    @GetMapping("/page")
    public R<Page<SetmealDto>> page(
            @RequestParam(value = "page", defaultValue = "1") Integer page,
            @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
            @RequestParam(value = "name", required = false) String name
    ) {
        Page<Setmeal> setmealPage = new Page<>(page, pageSize);
        LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<Setmeal>();
        queryWrapper.like(StringUtils.isNotEmpty(name), Setmeal::getName, name)
                .orderByDesc(Setmeal::getUpdateTime); // 排序
        setmealService.page(setmealPage, queryWrapper);
        Page<SetmealDto> setmealDtoPage = new Page<>();
        BeanUtils.copyProperties(setmealPage, setmealDtoPage, "records");
        List<SetmealDto> collect = setmealPage.getRecords().stream().map(item -> {
            SetmealDto setmealDto = new SetmealDto();
            BeanUtils.copyProperties(item, setmealDto);
            setmealDto.setCategoryName(categoryService.getById(item.getCategoryId()).getName());
            return setmealDto;
        }).collect(Collectors.toList());
        setmealDtoPage.setRecords(collect);
        return R.success(setmealDtoPage);
    }

    /**
     * 修改套餐状态
     *
     * @param statusType
     * @param ids
     * @return
     */
    /*修改套餐状态删除所有缓存数据*/
    @CacheEvict(allEntries = true)
    @ApiOperation("修改套餐状态接口")
    @PostMapping("/status/{statusType}")
    public R<String> updateStatus(
            @PathVariable("statusType") Integer statusType,
            @RequestParam("ids") List<Long> ids) {
        if (!Arrays.asList(0, 1).contains(statusType)) {
            return R.error("错误的状态");
        }
        LambdaUpdateWrapper<Setmeal> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.set(Setmeal::getStatus, statusType)
                .in(Setmeal::getId, ids);
        setmealService.update(updateWrapper);
        return R.success("修改状态成功");
    }


    /**
     * 删除套餐接口
     *
     * @param ids
     * @return
     */
    /* 删除套餐的时候，清除所有套餐缓存 */
    @CacheEvict(allEntries = true)
    @ApiOperation("删除套餐接口")
    @DeleteMapping
    public R<String> delete(@RequestParam("ids") List<Long> ids) {
        // 判断是否存在 在售套餐删除
        LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Setmeal::getStatus, 1).in(Setmeal::getId, ids);
        List<Setmeal> list = setmealService.list(queryWrapper);
        if (list.size() != 0) {
            return R.error("无法删除正在售卖的套餐");
        }
        setmealService.deleteWithSetmealDish(ids);
        return R.success("删除成功");
    }

    /**
     * 获取单个的菜品信息
     *
     * @param id
     * @return
     */
    @ApiOperation("通过id获取套餐信息")
    @GetMapping("{id}")
    public R<SetmealDto> get(@PathVariable("id") Long id) {
        SetmealDto result = new SetmealDto();
        Setmeal setmeal = setmealService.getById(id);
        LambdaQueryWrapper<SetmealDish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SetmealDish::getSetmealId, setmeal.getId());
        List<SetmealDish> setmealDishList = setmealDishService.list(queryWrapper);
        BeanUtils.copyProperties(setmeal, result);
        result.setSetmealDishes(setmealDishList);
        return R.success(result);
    }


    /* 删除缓存 */
    @CacheEvict(key = "@setmealDto.categoryId")
    @ApiOperation("修改套餐信息")
    @PutMapping
    public R<String> update(@RequestBody SetmealDto setmealDto) {
        setmealService.updateWithSetmealDish(setmealDto);
        return R.success("修改套餐成功");
    }

    /* 添加缓存*/
    @Cacheable(key = "#setmeal.categoryId + '_'+ #setmeal.status", unless = "#result.data == null")
    @ApiOperation("根据参数查询套餐")
    @GetMapping("/list")
    public R<List<Setmeal>> list(Setmeal setmeal) {
        LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(setmeal.getCategoryId() != null,
                Setmeal::getCategoryId, setmeal.getCategoryId())
                .eq(setmeal.getStatus() != null,
                        Setmeal::getStatus, setmeal.getStatus());
        List<Setmeal> list = setmealService.list(queryWrapper);
        return R.success(list);
    }

}
